package com.richapp.launcher.database.system.dao;

import java.sql.SQLException;
import java.util.List;

import com.j256.ormlite.stmt.UpdateBuilder;
import com.richapp.launcher.database.system.SystemBaseDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.utils.Constants;
import com.richapp.launcher.utils.Tools;

import android.content.Context;

import android.util.Log;

public class BoxModelDao extends SystemBaseDao<BoxModel>{

	public BoxModelDao(Context context) {
		super(context,BoxModel.class);
	}
	
	public BoxModel getCurrentBox(){
		BoxModel bm;
		String cpuId = null;
		String ip;
		String distributorId=null; //经销商id
		try {
			cpuId =Tools.getCPUSerial();
			List<String> ips = Tools.getAllIps(0);
			ip = "127.0.0.1";
			distributorId=Tools.getDistributorSerial();
			if(ips.size() > 0){
				ip = ips.get(0);
			}
			bm = getBoxByCpuId(cpuId);
			if(bm == null){
				bm = new BoxModel();
				bm.setBoxCpuId(cpuId);
				bm.setBoxInsideIp(ip);
				bm.setDistributorId(distributorId);
				bm.setStatus(Constants.BOX_STATUS_ONLINE);
				bm.setBoxName("主机"+cpuId.substring(cpuId.length()-4, cpuId.length()-1));
				gettOp().create(bm);
			}
			bm.setDistributorId(distributorId);
			bm = getBoxByCpuId(cpuId);
			bm.setBoxInsideIp(ip);
			gettOp().update(bm);
		} catch (SQLException e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		bm = getBoxByCpuId(cpuId);
		return bm;
	}
	
	public BoxModel getBoxByCpuId(String boxCpuId){
		BoxModel bm = null;
		try {
			bm = gettOp().queryBuilder().where().eq("boxCpuId", boxCpuId).queryForFirst();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return bm;
	}
	
	public void bindUnbindBoxWithUserId(String userName){
		try {
			UpdateBuilder<BoxModel, Integer> ub = gettOp().updateBuilder();
			ub.updateColumnValue("userName", userName);
			ub.update();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
	}
	
	public List<BoxModel> getBoxList(){
		List<BoxModel> boxList = null;
		try {
			boxList = gettOp().queryBuilder().query();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return boxList;
	}
	
	public List<BoxModel> getBoxList(String userName){
		List<BoxModel> boxList = null;
		try {
			boxList = gettOp().queryBuilder().where().eq("userName", userName).query();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return boxList;
	}


	public BoxModel getBoxModel(String userName,String maxLastHandelTime){
		BoxModel boxModel = null;
		try {
			boxModel = gettOp().queryBuilder().where().eq("userName", userName).and().eq("lastHandelTime",maxLastHandelTime).queryForFirst();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return boxModel;
	}


	
}
